<!-- 表单组件 -->
<template>
  <div class="account-box">
    <div class="toggle">
      <a href="javascript:;" @click="type = 'account'" v-if="type === 'mobile'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" @click="type = 'mobile'" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <!-- type为account时使用账号登录 -->
      <template v-if="type === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              type="text"
              placeholder="请输入用户名或手机号"
              v-model="account"
            />
          </div>
          <!-- 显示错误 -->
          <div class="error" v-if="accountError">
            <i class="iconfont icon-warning" />
            {{ accountError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
              type="password"
              placeholder="请输入密码"
              v-model="password"
            />
          </div>
          <!-- 显示错误 -->
          <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />
            {{ passwordError }}
          </div>
        </div>
      </template>
      <!-- type为mobile时使用手机号登录 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <!-- 手机号输入框啊绑定 ref -> mobileRef -->
            <input
              ref="mobileRef"
              v-model="mobile"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <!-- 显示错误 -->
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{ mobileError }}
          </div>
        </div>
        <!-- 验证码 -->
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="password" placeholder="请输入验证码" v-model="code" />
            <span class="code" @click="send">{{
              time === 0 ? "发送验证码" : `${time}s后发送`
            }}</span>
          </div>
          <!-- 显示错误 -->
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{ codeError }}
          </div>
        </div>
      </template>

      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <!-- 显示错误 -->
        <div class="error" v-if="isAgreeError">
          <i class="iconfont icon-warning" />
          {{ isAgreeError }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="handleLogin">登录</a>
    </div>
    <div class="action">
      <!-- 打开弹窗 -->
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
        ><img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt="QQ登录"
          border="0"
      /></a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="LoginForm">
import { ref } from "vue";
import Message from "@/components/message";
import useStore from "@/store";
import { useRoute, useRouter } from "vue-router";
// 导入函数 useField 可以返回需要和 input 框绑定的字段 value，和 errorMessage
import { useField, useForm } from "vee-validate";
import { watch } from "vue";
import { useCountDown } from "@/hooks";
import { accountRule, passwordRule, mobileRule, codeRule, isAgreeRule } from '@/utils/validate'

// resetForm 切换时重置表单校验
const { validate, resetForm } = useForm({
  // 指定默认值
  initialValues: {
    account: 'cdshi0001',
    password: '123456',
    mobile: '13012345678',
    code: '123456',
    isAgree: true,
  },
  validationSchema: {
    account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule,
    mobile: mobileRule,
    code: codeRule,
  },
})

// 通过 useField 提供 value 值和错误信息
const { value: account, errorMessage: accountError } = useField<string>('account')
const { value: password, errorMessage: passwordError } = useField<string>('password')
const { value: isAgree, errorMessage: isAgreeError } = useField<boolean>('isAgree')
const { value: mobile, errorMessage: mobileError, validate: validateMobile } = useField<string>('mobile')
const { value: code, errorMessage: codeError } = useField<string>('code')

const { user,cart } = useStore();
const router = useRouter();
const route = useRoute()
const type = ref<"account" | "mobile">("account");
// const route = useRouter()
// 点击登录 -> 发送请求
const handleLogin = async () => {
  // 统一校验
  const res = await validate();
  // 根据type.value按需校验 -> res.errors
  try {
    if (type.value === "account") {
      // 账号登录 -> 传过去的数据应该是 account.value 和 password.value
      if (res.errors.account || res.errors.password || res.errors.isAgree) return //校验
      await user.login(account.value, password.value);
    } else {
      // 短信登录
      if (res.errors.mobile || res.errors.code || res.errors.isAgree) return //校验
      await user.mobileLogin(mobile.value, code.value); 
    }
    // 登录成功后，合并购物车
    cart.mergeLocalCart()
    // 弹框提示
    Message.success("登录成功");
    // 跳转
    const redirectUrl = (route.query.redirectUrl as string) || '/'
    router.push(redirectUrl)
  } catch {
    Message.error("登录失败");
  }
};
// 点击发送验证码 校验手机号
const mobileRef = ref<HTMLInputElement | null>(null);
const { time, start } = useCountDown(60);

const send = async () => {
  if (time.value > 0) return; //定时器还没结束 不允许发送验证码
  // 单独校验手机号
  const res = await validateMobile();
  if (!res.valid) {
    // 校验不通过
    mobileRef.value?.focus();
    return;
  }
  // 校验通过 -> 触发action中的发送验证码请求方法
  try {
    await user.sendMobileMsg(mobile.value);
    Message.success("获取验证码成功");
    // 使用倒计时
    start(10);
  } catch (error) {
    Message.error("获取验证码失败");
  }
};
// 监听type 的变化
watch(type, () => {
  // 重置表单
  resetForm();
});
</script>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
